<template>
  <AdminNavbar />
  <div class="admin-container">
    <el-container>
      <el-aside width="160px">
        <el-menu
          :default-active="activeMenu"
          class="admin-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="movies">
            <el-icon><VideoPlay /></el-icon>
            <span>影片管理</span>
          </el-menu-item>
          <el-menu-item index="orders">
            <el-icon><List /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          <el-menu-item index="reviews">
            <el-icon><ChatSquare /></el-icon>
            <span>影评管理</span>
          </el-menu-item>
          <el-menu-item index="showtimes">
            <el-icon><Ticket /></el-icon>
            <span>场次管理</span>
          </el-menu-item>
          <el-menu-item index="users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="stats">
            <el-icon><DataAnalysis /></el-icon>
            <span>数据统计</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-container>
        <el-main>
          <!-- Movies Management -->
          <div v-if="activeMenu === 'movies'">
            <div class="action-bar">
              <div class="left-actions">
                <el-button type="primary" @click="showAddMovieDialog">
                  添加电影
                </el-button>
                <el-button
                  type="danger"
                  @click="batchDeleteMovies"
                  :disabled="selectedMovies.length === 0"
                >
                  批量删除
                </el-button>
                <span v-if="selectedMovies.length > 0" class="selection-info">
                  已选择 {{ selectedMovies.length }} 项
                </span>
              </div>

              <div class="search-container">
                <el-input
                  v-model="movieTitleSearch"
                  placeholder="电影名称"
                  style="width: 150px; margin-left: 16px;"
                  clearable
                  @keyup.enter="searchMovies"
                />
                <el-input
                  v-model="movieDirectorSearch"
                  placeholder="导演"
                  style="width: 150px; margin-left: 8px;"
                  clearable
                  @keyup.enter="searchMovies"
                />
                <el-select
                  v-model="movieStatusSearch"
                  placeholder="状态"
                  style="width: 150px; margin-left: 8px;"
                  clearable
                  @change="searchMovies"
                >
                  <el-option label="正在热映" value="正在热映" />
                  <el-option label="即将上映" value="即将上映" />
                </el-select>
                <el-button type="primary" @click="searchMovies" style="width: 80px; margin-left: 4px;">
                  搜索
                </el-button>
                <el-button type="info" @click="resetMovieSearch" style="width: 80px; margin-left: 4px;">
                  重置
                </el-button>
              </div>
            </div>

            <el-table
              :data="paginatedMovies"
              style="width: 100%"
              :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#606266',
                fontWeight: 'bold',
                textAlign: 'center'
              }"
              :cell-style="{
                textAlign: 'center'
              }"
              class="larger-font-table"
              @selection-change="handleMovieSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column type="index" label="编号" width="70" align="center" />
              <el-table-column prop="title" label="电影名称" align="center" />
              <el-table-column prop="director" label="导演" width="120" align="center" />
              <el-table-column prop="releaseDate" label="上映日期" width="120" align="center" />
              <el-table-column prop="duration" label="时长" width="80" align="center">
                <template #default="scope">
                  {{ scope.row.duration }}分钟
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100" align="center">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status === '正在热映' ? 'success' : scope.row.status === '即将上映' ? 'warning' : 'info'"
                  >
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click="editMovie(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteMovie(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :total="filteredMovies.length"
                layout="total, prev, pager, next, jumper"
                @current-change="handlePageChange"
              />
            </div>
          </div>

          <!-- Users Management -->
          <div v-if="activeMenu === 'users'" class="users-management">
            <div class="action-bar">
              <div class="left-actions">
                <span v-if="selectedUsers.length > 0" class="selection-info">
                  已选择 {{ selectedUsers.length }} 项
                </span>
              </div>

              <div class="search-container">
                <el-input
                  v-model="userKeywordSearch"
                  placeholder="搜索用户名/邮箱/手机号"
                  style="width: 200px;"
                  clearable
                  @keyup.enter="searchUsers"
                />
                <el-button type="primary" @click="searchUsers" style="width: 80px; margin-left: 8px;">
                  搜索
                </el-button>
                <el-button type="info" @click="resetUserSearch" style="width: 80px; margin-left: 4px;">
                  重置
                </el-button>
              </div>
            </div>

            <el-table
              :data="users"
              style="width: 100%"
              :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#606266',
                fontWeight: 'bold',
                textAlign: 'center'
              }"
              :cell-style="{
                textAlign: 'center'
              }"
              class="larger-font-table"
              v-loading="loadingUsers"
              @selection-change="handleUserSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column type="index" label="序号" width="70" align="center" />
              <el-table-column prop="username" label="用户名" align="center" min-width="120" />
              <el-table-column prop="email" label="邮箱" align="center" min-width="180" />
              <el-table-column prop="phone" label="手机号" align="center" min-width="120" />
              <el-table-column prop="address" label="地址" align="center" min-width="150" />
              <el-table-column prop="balance" label="余额" align="center" width="100">
                <template #default="scope">
                  ¥{{ scope.row.balance?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="registerTime" label="注册时间" align="center" min-width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.registerTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click="viewUserDetail(scope.row)"
                  >
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 用户分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="userCurrentPage"
                :page-size="userPageSize"
                :total="userTotal"
                layout="total, prev, pager, next, jumper"
                @current-change="handleUserPageChange"
              />
            </div>
          </div>

          <!-- Orders Management -->
          <div v-if="activeMenu === 'orders'" class="orders-management">

            <div class="order-search">
              <el-form :inline="true" class="search-form">
                <el-form-item label="订单号">
                  <el-input
                    v-model="orderNumberSearch"
                    placeholder="请输入订单号"
                    clearable
                    @keyup.enter="searchOrders"
                  />
                </el-form-item>
                <el-form-item label="用户名">
                  <el-input
                    v-model="orderUserSearch"
                    placeholder="请输入用户名"
                    clearable
                    @keyup.enter="searchOrders"
                  />
                </el-form-item>
                <el-form-item label="电影名称">
                  <el-input
                    v-model="orderMovieSearch"
                    placeholder="请输入电影名称"
                    clearable
                    @keyup.enter="searchOrders"
                  />
                </el-form-item>
                <el-form-item label="日期范围">
                  <el-date-picker
                    v-model="orderDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="searchOrders"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchOrders">搜索</el-button>
                  <el-button type="info" @click="resetOrderSearch">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table
              :data="paginatedOrders"
              style="width: 100%"
              :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#606266',
                fontWeight: 'bold',
                textAlign: 'center'
              }"
              :cell-style="{
                textAlign: 'center'
              }"
              border
              stripe
              class="larger-font-table"
              v-loading="loadingOrders"
            >
              <el-table-column type="index" label="序号" width="60" align="center" fixed />
              <el-table-column prop="orderNumber" label="订单号" min-width="180" align="center" />
              <el-table-column label="用户" min-width="100" align="center">
                <template #default="scope">
                  {{ scope.row.user?.username || '未知用户' }}
                </template>
              </el-table-column>
              <el-table-column label="电影" min-width="150" align="center">
                <template #default="scope">
                  {{ scope.row.movie?.title || '未知电影' }}
                </template>
              </el-table-column>
              <el-table-column prop="orderTime" label="下单时间" min-width="180" align="center" />
              <el-table-column prop="price" label="总金额" min-width="100" align="center">
                <template #default="scope">
                  ¥{{ scope.row.price.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100" align="center">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status === 1 ? 'success' :
                          scope.row.status === 2 ? 'info' :
                          scope.row.status === 0 ? 'warning' : 'primary'"
                  >
                    {{ scope.row.status === 0 ? '待支付' :
                       scope.row.status === 1 ? '已完成' :
                       scope.row.status === 2 ? '已取消' : '未知状态' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="200" align="center" fixed="right">
                <template #default="scope">
                  <!-- 查看详情按钮已移除 -->
                  <el-button
                    v-if="scope.row.status === 0"
                    size="small"
                    type="danger"
                    @click="cancelOrder(scope.row)"
                  >
                    取消订单
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 订单分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="orderCurrentPage"
                :page-size="pageSize"
                :total="orderTotal"
                layout="total, prev, pager, next, jumper"
                @current-change="handleOrderPageChange"
              />
            </div>
          </div>

          <!-- Reviews Management -->
          <div v-if="activeMenu === 'reviews'">
            <div class="action-bar">
              <div class="search-container">
                <el-input
                  v-model="reviewMovieTitleSearch"
                  placeholder="电影名称"
                  style="width: 150px;"
                  clearable
                  @keyup.enter="searchReviews"
                />
                <el-input
                  v-model="reviewUserSearch"
                  placeholder="用户名"
                  style="width: 150px; margin-left: 8px;"
                  clearable
                  @keyup.enter="searchReviews"
                />
                <el-select
                  v-model="reviewRatingSearch"
                  placeholder="评分"
                  style="width: 120px; margin-left: 8px;"
                  clearable
                  @change="searchReviews"
                >
                  <el-option v-for="i in 5" :key="i" :label="`${i}星`" :value="i" />
                </el-select>
                <el-button type="primary" @click="searchReviews" style="width: 80px; margin-left: 4px;">
                  搜索
                </el-button>
                <el-button type="info" @click="resetReviewSearch" style="width: 80px; margin-left: 4px;">
                  重置
                </el-button>
              </div>
            </div>

            <el-table
              :data="paginatedReviews"
              style="width: 100%"
              :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#606266',
                fontWeight: 'bold',
                textAlign: 'center'
              }"
              :cell-style="{
                textAlign: 'center'
              }"
              class="larger-font-table"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="电影" align="center" width="180">
                <template #default="scope">
                  {{ scope.row.movie?.title || '未知电影' }}
                </template>
              </el-table-column>
              <el-table-column label="用户" align="center" width="120">
                <template #default="scope">
                  {{ scope.row.user?.username || '未知用户' }}
                </template>
              </el-table-column>
              <el-table-column prop="rating" label="评分" width="150" align="center">
                <template #default="scope">
                  <span style="margin-right: 5px;">({{ scope.row.rating }})</span>
                  <el-rate
                    v-model="scope.row.rating"
                    :max="5"
                    disabled
                    text-color="#ff9900"
                    style="display: inline-flex; min-width: 120px;"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="comment" label="评论内容" align="center">
                <template #default="scope">
                  <div class="review-content-cell">{{ scope.row.comment }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="reviewTime" label="评论时间" width="180" align="center" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                    <el-button
                      size="small"
                    type="danger"
                    @click="deleteReview(scope.row)"
                    >
                    删除
                    </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 影评分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="reviewCurrentPage"
                :page-size="pageSize"
                :total="reviewTotal"
                layout="total, prev, pager, next, jumper"
                @current-change="handleReviewPageChange"
              />
            </div>
          </div>

          <!-- Showtime Management -->
          <div v-if="activeMenu === 'showtimes'">
            <div class="action-bar">
              <div class="left-actions">
                <el-button type="primary" @click="showAddShowtimeDialog">
                  添加场次
                </el-button>
              </div>

              <div class="search-container">
                <el-select
                  v-model="showtimeMovieSearch"
                  placeholder="选择电影"
                  clearable
                  filterable
                  style="width: 180px;"
                  @change="searchShowtimes"
                >
                  <el-option
                    v-for="movie in movies"
                    :key="movie.id"
                    :label="movie.title"
                    :value="movie.id"
                  />
                </el-select>
                <el-select
                  v-model="showtimeHallSearch"
                  placeholder="选择影厅"
                  clearable
                  style="width: 150px; margin-left: 8px;"
                  @change="searchShowtimes"
                >
                  <el-option label="1号厅" value="1号厅" />
                  <el-option label="2号厅" value="2号厅" />
                  <el-option label="3号厅" value="3号厅" />
                  <el-option label="4号厅" value="4号厅" />
                  <el-option label="5号厅" value="5号厅" />
                  <el-option label="6号厅" value="6号厅" />
                </el-select>
                <el-date-picker
                  v-model="showtimeDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 260px; margin-left: 8px;"
                  @change="searchShowtimes"
                />
                <el-button type="primary" @click="searchShowtimes" style="width: 80px; margin-left: 4px;">
                  搜索
                </el-button>
                <el-button type="info" @click="resetShowtimeSearch" style="width: 80px; margin-left: 4px;">
                  重置
                </el-button>
              </div>
            </div>

            <!-- 场次列表 -->
            <el-table
              :data="paginatedShowtimes"
              style="width: 100%"
              :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#606266',
                fontWeight: 'bold',
                textAlign: 'center'
              }"
              :cell-style="{
                textAlign: 'center'
              }"
              class="larger-font-table"
              v-loading="loadingShowtimes"
            >
              <el-table-column type="index" label="序号" width="70" align="center" />
              <el-table-column label="电影名称" align="center">
                <template #default="scope">
                  {{ scope.row.movie?.title || '未知电影' }}
                </template>
              </el-table-column>
              <el-table-column prop="hallName" label="影厅" width="120" align="center" />
              <el-table-column prop="showTime" label="放映时间" width="220" align="center">
                <template #default="scope">
                  {{ formatShowtime(scope.row.showTime, scope.row.movie) }}
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格" width="100" align="center">
                <template #default="scope">
                  ¥{{ scope.row.price?.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="availableSeats" label="可用座位" width="100" align="center">
                <template #default="scope">
                  {{ scope.row.availableSeats }}/100
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="primary"
                    @click="editShowtime(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteShowtime(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 场次分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="showtimeCurrentPage"
                :page-size="pageSize"
                :total="showtimeTotal"
                layout="total, prev, pager, next, jumper"
                @current-change="handleShowtimePageChange"
              />
            </div>
          </div>

          <!-- Stats -->
          <div v-if="activeMenu === 'stats'" class="stats-management">
            <div class="stats-overview">
              <h3 style="margin-bottom: 20px;">数据概览</h3>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">{{ overviewStats.totalUsers || 0 }}</div>
                      <div class="stats-label">总用户数</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">{{ overviewStats.totalMovies || 0 }}</div>
                      <div class="stats-label">总电影数</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">{{ overviewStats.totalOrders || 0 }}</div>
                      <div class="stats-label">总订单数</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">¥{{ (overviewStats.totalRevenue || 0).toFixed(2) }}</div>
                      <div class="stats-label">总收入</div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>

              <el-row :gutter="20" style="margin-top: 20px;">
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">{{ overviewStats.todayOrders || 0 }}</div>
                      <div class="stats-label">今日订单</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">¥{{ (overviewStats.todayRevenue || 0).toFixed(2) }}</div>
                      <div class="stats-label">今日收入</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">{{ overviewStats.activeUsers || 0 }}</div>
                      <div class="stats-label">活跃用户</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stats-card">
                    <div class="stats-item">
                      <div class="stats-value">{{ ((overviewStats.activeUsers || 0) / (overviewStats.totalUsers || 1) * 100).toFixed(1) }}%</div>
                      <div class="stats-label">活跃率</div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>

            <div class="stats-charts" style="margin-top: 30px;">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <div class="card-header">
                        <span>用户增长趋势</span>
                      </div>
                    </template>
                    <div class="chart-container">
                      <div class="simple-chart">
                        <div v-for="(item, index) in userGrowthData" :key="index" class="chart-item">
                          <div class="chart-label">{{ item.date }}</div>
                          <div class="chart-bar-container">
                            <div 
                              class="chart-bar" 
                              :style="{ height: (item.newUsers / 25 * 100) + '%' }"
                            ></div>
                          </div>
                          <div class="chart-value">{{ item.newUsers }}</div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <div class="card-header">
                        <span>收入统计</span>
                      </div>
                    </template>
                    <div class="chart-container">
                      <div class="simple-chart">
                        <div v-for="(item, index) in revenueData" :key="index" class="chart-item">
                          <div class="chart-label">{{ item.date }}</div>
                          <div class="chart-bar-container">
                            <div 
                              class="chart-bar revenue-bar" 
                              :style="{ height: (item.revenue / 7000 * 100) + '%' }"
                            ></div>
                          </div>
                          <div class="chart-value">¥{{ Math.round(item.revenue) }}</div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>

              <el-row :gutter="20" style="margin-top: 20px;">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <div class="card-header">
                        <span>热门电影排行</span>
                      </div>
                    </template>
                    <el-table :data="popularMovies" style="width: 100%">
                      <el-table-column prop="title" label="电影名称" align="center" />
                      <el-table-column prop="ticketsSold" label="售票数" align="center" />
                      <el-table-column prop="revenue" label="收入" align="center">
                        <template #default="scope">
                          ¥{{ scope.row.revenue.toFixed(2) }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="rating" label="评分" align="center">
                        <template #default="scope">
                          {{ scope.row.rating }}分
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <div class="card-header">
                        <span>用户分布</span>
                      </div>
                    </template>
                    <div class="distribution-container">
                      <div class="distribution-section">
                        <h4>年龄分布</h4>
                        <div v-for="item in userDistribution.ageDistribution" :key="item.ageGroup" class="distribution-item">
                          <div class="distribution-label">{{ item.ageGroup }}</div>
                          <div class="distribution-bar-container">
                            <div 
                              class="distribution-bar" 
                              :style="{ width: item.count + '%' }"
                            ></div>
                          </div>
                          <div class="distribution-value">{{ item.count }}%</div>
                        </div>
                      </div>
                      <div class="distribution-section" style="margin-top: 20px;">
                        <h4>地区分布</h4>
                        <div v-for="item in userDistribution.regionDistribution" :key="item.region" class="distribution-item">
                          <div class="distribution-label">{{ item.region }}</div>
                          <div class="distribution-bar-container">
                            <div 
                              class="distribution-bar region-bar" 
                              :style="{ width: item.count + '%' }"
                            ></div>
                          </div>
                          <div class="distribution-value">{{ item.count }}%</div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 添加/编辑电影对话框 -->
    <el-dialog
            v-model="movieDialogVisible"
            :title="isEditingMovie ? '编辑电影' : '添加电影'"
            width="700px"
            :close-on-click-modal="false"
    >
      <el-form
              :model="movieForm"
              :rules="movieRules"
              ref="movieFormRef"
              label-width="120px"
              class="movie-form"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="电影名称" prop="title">
                    <el-input v-model="movieForm.title" placeholder="请输入电影名称" />
        </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="导演" prop="director">
                    <el-input v-model="movieForm.director" placeholder="请输入导演" />
        </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="上映日期" prop="releaseDate">
                    <el-date-picker
                      v-model="movieForm.releaseDate"
                      type="date"
                      placeholder="选择上映日期"
                      style="width: 100%;"
                      value-format="YYYY-MM-DD"
                    />
        </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="片长(分钟)" prop="duration">
                    <el-input-number
                      v-model="movieForm.duration"
                      :min="1"
                      :max="999"
                      style="width: 100%;"
                    />
        </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="主演" prop="actors">
                    <el-input
                      v-model="movieForm.actors"
                      placeholder="多位演员使用逗号分隔"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="类型" prop="genre">
                    <el-input
                      v-model="movieForm.genre"
                      placeholder="多个类型使用逗号分隔"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="状态" prop="status">
                    <el-select v-model="movieForm.status" placeholder="请选择电影状态" style="width: 100%;">
                      <el-option label="正在热映" value="正在热映" />
                      <el-option label="即将上映" value="即将上映" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="简介" prop="description">
          <el-input
                  v-model="movieForm.description"
            type="textarea"
            :rows="4"
                  placeholder="请输入电影简介"
          />
        </el-form-item>

              <el-form-item>
                <div style="display: flex; justify-content: flex-end;">
                  <el-button @click="movieDialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="submitMovieForm" :loading="submittingMovie">确认</el-button>
                </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 订单详情对话框已移除 -->

    <!-- 添加/编辑场次对话框 -->
    <el-dialog
            v-model="showtimeDialogVisible"
            :title="isEditingShowtime ? '编辑场次' : '添加场次'"
            width="600px"
            :close-on-click-modal="false"
    >
      <div class="form-tip" style="margin-bottom: 15px;">注意：每个影厅固定为100个座位</div>
      <el-form
              :model="showtimeForm"
              :rules="showtimeRules"
              ref="showtimeFormRef"
              label-width="100px"
            >
        <el-form-item label="选择电影" prop="movieId">
          <el-select v-model="showtimeForm.movieId" placeholder="请选择电影" filterable style="width: 100%;">
            <el-option
                    v-for="movie in nowPlayingMovies"
                    :key="movie.id"
                    :label="movie.title"
                    :value="movie.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择影厅" prop="hallName">
          <el-select v-model="showtimeForm.hallName" placeholder="请选择影厅" style="width: 100%;">
            <el-option label="1号厅" value="1号厅" />
            <el-option label="2号厅" value="2号厅" />
            <el-option label="3号厅" value="3号厅" />
            <el-option label="4号厅" value="4号厅" />
            <el-option label="5号厅" value="5号厅" />
            <el-option label="6号厅" value="6号厅" />
          </el-select>
        </el-form-item>
        <el-form-item label="放映时间" prop="showTime">
          <el-date-picker
                  v-model="showtimeForm.showTime"
                  type="datetime"
                  placeholder="选择放映时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="showtimeForm.price" :precision="2" :step="1" :min="0" style="width: 100%;"/>
        </el-form-item>
        <!-- 座位数固定为100，不再显示此选项 -->
        <el-form-item>
          <div style="display: flex; justify-content: flex-end;">
            <el-button @click="showtimeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitShowtimeForm" :loading="submittingShowtime">{{ isEditingShowtime ? '确认修改' : '确认添加' }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { List, VideoPlay, ChatSquare, Ticket, User, DataAnalysis } from '@element-plus/icons-vue'
import { useUserStore } from '../store/user'
import AdminNavbar from '../components/AdminNavbar.vue'
import axiosInstance from '../utils/axiosInstance'
import { adminUserApi, adminStatsApi } from '../api/admin'

interface Movie {
  id: number;
  title: string;
  director: string;
  actors?: string;
  genre?: string;
  releaseDate: string;
  duration: number;
  description?: string;
  status: string;
}

interface Order {
  id: number;
  orderNumber: string;
  orderTime: string;
  status: number; // 0=待支付, 1=已完成, 2=已取消
  price: number;
  user?: {
    id: number;
    username: string;
  };
  movie?: {
    id: number;
    title: string;
  };
  showtime?: {
    id: number;
    hallName: string;
    showTime: string;
    price: number;
  };
  seatInfo?: string;
}

interface Review {
  id: number;
  comment: string;
  rating: number;
  reviewTime: string;
  user: {
    id: number;
    username: string;
  };
  movie: {
    id: number;
    title: string;
  };
}

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const activeMenu = ref('movies')
// 旧的搜索关键字（保留以防其他地方还在使用）
const movieSearchKeyword = ref('')
// 电影搜索字段
const movieTitleSearch = ref('')
const movieDirectorSearch = ref('')
const movieStatusSearch = ref('')

// 分页相关
const currentPage = ref(1)
const orderCurrentPage = ref(1)
const reviewCurrentPage = ref(1)
const pageSize = ref(10) // 每页显示10条数据
const orderTotal = ref(0) // 订单总数
const reviewTotal = ref(0) // 影评总数

const movies = ref<Movie[]>([])
const orders = ref<Order[]>([])
const reviews = ref<Review[]>([])

// 电影选择相关
const selectedMovies = ref<Movie[]>([])
const isAllMoviesSelected = ref(false)

// 订单相关变量
const orderNumberSearch = ref('')
const orderUserSearch = ref('')
const orderMovieSearch = ref('')
const orderDateRange = ref<[Date, Date] | null>(null)
const loadingOrders = ref(false)

// 影评相关变量
const reviewMovieTitleSearch = ref('')
const reviewUserSearch = ref('')
const reviewRatingSearch = ref<number | null>(null)

// 场次管理相关变量
const showtimeDialogVisible = ref(false)
const submittingShowtime = ref(false)
const isEditingShowtime = ref(false)
const showtimeFormRef = ref()
const showtimeForm = ref({
  id: 0,
  movieId: null as number | null,
  hallName: '',
  showTime: '', // 使用 YYYY-MM-DD HH:mm:ss 格式
  price: 50.00,
  availableSeats: 100
})
// 场次表单验证规则
const showtimeRules = {
  movieId: [{ required: true, message: '请选择电影', trigger: 'change' }],
  hallName: [{ required: true, message: '请选择影厅', trigger: 'change' }],
  showTime: [{ required: true, message: '请选择放映时间', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}
// 场次列表相关变量
const showtimes = ref<any[]>([])
const showtimeTotal = ref(0)
const showtimeCurrentPage = ref(1)
const loadingShowtimes = ref(false)
// 场次搜索相关变量
const showtimeMovieSearch = ref<number | null>(null)
const showtimeHallSearch = ref('')
const showtimeDateRange = ref<[Date, Date] | null>(null)

// 用户管理相关变量
const users = ref<any[]>([])
const userTotal = ref(0)
const userCurrentPage = ref(1)
const userPageSize = ref(10)
const loadingUsers = ref(false)
const selectedUsers = ref<any[]>([])
const userKeywordSearch = ref('')

// 数据统计相关变量
const overviewStats = ref<any>({})
const userGrowthData = ref<any[]>([])
const revenueData = ref<any[]>([])
const popularMovies = ref<any[]>([])
const userDistribution = ref<any>({})
const userGrowthChart = ref()
const revenueChart = ref()
const userDistributionChart = ref()

// 在组件挂载时加载数据
onMounted(async () => {
  console.log('Admin.vue onMounted start'); // 日志：开始
  if (!userStore.isLoggedIn || !userStore.isAdmin) {
    ElMessage.warning('请先登录管理员账号')
    router.push('/login')
    return
  }
  console.log('Admin.vue user check passed'); // 日志：用户检查通过

  // 检查URL查询参数中是否有指定的活动菜单
  const queryActiveMenu = route.query.activeMenu as string;
  console.log('Admin.vue route.query.activeMenu:', queryActiveMenu); // 日志：读取到的URL参数
  if (queryActiveMenu && ['movies', 'orders', 'reviews', 'showtimes', 'users', 'stats'].includes(queryActiveMenu)) {
    activeMenu.value = queryActiveMenu;
    console.log('Admin.vue activeMenu set from query:', activeMenu.value); // 日志：从URL设置后的值
  } else {
      console.log('Admin.vue No valid activeMenu in query, default is:', activeMenu.value); // 日志：未使用URL参数时的默认值
  }

  // 加载电影数据
  try {
      console.log('Admin.vue Loading movies...'); // 日志：开始加载电影
    const response = await axiosInstance.get('/admin/movies');
    if (response.data && Array.isArray(response.data)) {
      movies.value = response.data;
    }
     console.log('Admin.vue Movies loaded.'); // 日志：电影加载完成
  } catch (error) {
    console.error('加载电影数据失败:', error);
    ElMessage.error('加载电影数据失败');
  }

  // 加载订单数据
   try {
      console.log('Admin.vue Loading orders...'); // 日志：开始加载订单
      await loadOrdersFromServer();
      console.log('Admin.vue Orders loaded.'); // 日志：订单加载完成
   } catch(error) {
       console.error('Error in loadOrdersFromServer during onMounted:', error); // 日志：加载订单出错
   }

  // 加载影评数据 (如果需要)
  console.log('Admin.vue Checking if activeMenu is reviews:', activeMenu.value); // 日志：检查是否是影评页
  if (activeMenu.value === 'reviews') {
    console.log('Admin.vue Attempting to load reviews in onMounted...'); // 日志：尝试加载影评
    try {
      await loadReviewsFromServer();
      console.log('Admin.vue Reviews loaded in onMounted.'); // 日志：影评加载完成
  } catch (error) {
        console.error('Error in loadReviewsFromServer during onMounted:', error); // 日志：加载影评出错
    }
  }
   console.log('Admin.vue onMounted end. Final activeMenu:', activeMenu.value); // 日志：onMounted 结束及最终 activeMenu 值

  // 修改：在 onMounted 中也加载电影列表，供添加场次使用
  // 如果之前已经加载过，可以考虑优化，避免重复加载
  if (movies.value.length === 0) {
      console.log('Admin.vue Loading movies for showtime form...');
      try {
        const response = await axiosInstance.get('/admin/movies');
        if (response.data && Array.isArray(response.data)) {
          movies.value = response.data;
        }
         console.log('Admin.vue Movies loaded for showtime form.');
      } catch (error) {
        console.error('加载电影数据失败(for showtime): ', error);
      }
  }

  // 切换到场次管理时，确保电影列表已加载并加载场次数据
  if (activeMenu.value === 'showtimes') {
      console.log('Admin.vue Loading movies for showtime tab...');
      try {
        if (movies.value.length === 0) {
          const response = await axiosInstance.get('/admin/movies');
          if (response.data && Array.isArray(response.data)) {
            movies.value = response.data;
          }
          console.log('Admin.vue Movies loaded for showtime tab.');
        }

        // 加载场次列表
        await loadShowtimesFromServer();
        console.log('Admin.vue Showtimes loaded.');
      } catch (error) {
        console.error('加载场次管理数据失败: ', error);
      }
  }

  // 初始化用户管理数据
  if (activeMenu.value === 'users') {
    await loadUsersFromServer();
  }

  // 初始化数据统计
  if (activeMenu.value === 'stats') {
    await loadStatsData();
  }
})

// 菜单处理
const handleMenuSelect = async (index: string) => {
  activeMenu.value = index
  // 更新URL查询参数，不刷新页面
  router.replace({
    query: {
      ...route.query,
      activeMenu: index
    }
  })

  // 根据选择的菜单项加载对应的数据
  if (index === 'movies') {
    // 假设电影数据在 onMounted 中已加载或有单独加载函数
    // 如果需要每次切换都刷新，则调用 fetchMovies() 或类似函数
  } else if (index === 'orders') {
    loadOrdersFromServer(); // 切换到订单时加载订单
  } else if (index === 'reviews') {
    loadReviewsFromServer(); // 切换到影评时加载影评
  } else if (index === 'showtimes') {
    // 切换到场次管理时，确保电影列表已加载
    if (movies.value.length === 0) {
      console.log('Admin.vue Loading movies for showtime tab...');
      try {
        const response = await axiosInstance.get('/admin/movies');
        if (response.data && Array.isArray(response.data)) {
          movies.value = response.data;
        }
         console.log('Admin.vue Movies loaded for showtime tab.');
      } catch (error) {
        console.error('加载电影数据失败(for showtime tab): ', error);
      }
    }
    // 加载场次列表
    loadShowtimesFromServer();
  } else if (index === 'users') {
    loadUsersFromServer(); // 切换到用户管理时加载用户数据
  } else if (index === 'stats') {
    loadStatsData(); // 切换到数据统计时加载统计数据
  }
}

// 电影搜索函数
const searchMovies = () => {
  console.log('执行电影搜索，条件：', {
    title: movieTitleSearch.value,
    director: movieDirectorSearch.value,
    status: movieStatusSearch.value
  })
  // 搜索逻辑已在 filteredMovies 计算属性中实现
}

// 处理电影选择变化
const handleMovieSelectionChange = (selection: Movie[]) => {
  selectedMovies.value = selection
  // 检查是否全选
  isAllMoviesSelected.value = selection.length > 0 && selection.length === paginatedMovies.value.length
}

// 切换电影全选/取消全选
const toggleMovieSelectAll = () => {
  const tableRef = document.querySelector('.el-table__header-wrapper th.el-table-column--selection .el-checkbox') as HTMLElement
  if (tableRef) {
    tableRef.click()
  }
}

// 批量删除电影
const batchDeleteMovies = () => {
  if (selectedMovies.value.length === 0) {
    ElMessage.warning('请先选择要删除的电影')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedMovies.value.length} 部电影吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 获取所有选中电影的ID
      const movieIds = selectedMovies.value.map(movie => movie.id)

      // 调用后端API批量删除电影
      await axiosInstance.post('/admin/movies/batch-delete', { movieIds: movieIds })

      // 从列表中移除已删除的电影
      movies.value = movies.value.filter(movie => !movieIds.includes(movie.id))

      // 清空选择
      selectedMovies.value = []

      ElMessage.success('批量删除成功')
    } catch (error: any) {
      console.error('批量删除电影失败:', error)
      if (error.response && error.response.data) {
        ElMessage.error(`批量删除电影失败: ${error.response.data}`)
      } else {
        ElMessage.error('批量删除电影失败')
      }
    }
  }).catch(() => {})
}

// 重置电影搜索
const resetMovieSearch = () => {
  movieTitleSearch.value = ''
  movieDirectorSearch.value = ''
  movieStatusSearch.value = ''
  currentPage.value = 1 // 重置为第一页
}

// 订单搜索函数
const searchOrders = async () => {
  console.log('执行订单搜索，条件：', {
    orderNumber: orderNumberSearch.value,
    user: orderUserSearch.value,
    movie: orderMovieSearch.value,
    date: orderDateRange.value
  })

  // 如果没有搜索条件，重新从服务器获取数据
  if (!orderNumberSearch.value && !orderUserSearch.value && !orderMovieSearch.value && !orderDateRange.value) {
    await loadOrdersFromServer()
  }
  // 有搜索条件时，使用本地过滤（filteredOrders计算属性）
}

// 重置订单搜索
const resetOrderSearch = async () => {
  orderNumberSearch.value = ''
  orderUserSearch.value = ''
  orderMovieSearch.value = ''
  orderDateRange.value = null
  orderCurrentPage.value = 1 // 重置为第一页

  // 重新从服务器加载数据
  await loadOrdersFromServer()
}

// 从服务器加载订单数据
const loadOrdersFromServer = async () => {
  loadingOrders.value = true
  try {
    // 准备查询参数
    const params: Record<string, any> = {
      page: orderCurrentPage.value - 1, // 后端从0开始计数
      size: pageSize.value,
    }

    if (orderNumberSearch.value) {
      params.orderNumber = orderNumberSearch.value
    }

    if (orderUserSearch.value) {
      params.username = orderUserSearch.value
    }

    if (orderMovieSearch.value) {
      params.movieTitle = orderMovieSearch.value
    }

    if (orderDateRange.value && orderDateRange.value.length === 2) {
      const [startDate, endDate] = orderDateRange.value
      params.startDate = startDate.toISOString().split('T')[0]
      params.endDate = endDate.toISOString().split('T')[0]
    }

    console.log('加载订单数据，参数:', params)

    // 修改为调用管理员的分页接口，并使用正确的路径
    const response = await axiosInstance.get('/orders/admin/paged', { params })
    console.log('订单数据响应:', response.data)

    if (response.data) {
      // 假设后端返回 { content: [...], totalElements: ... }
      orders.value = response.data.content || []
      orderTotal.value = response.data.totalElements || 0
    }
  } catch (error) {
    console.error('加载订单数据失败:', error)
    ElMessage.error('加载订单数据失败')
    orders.value = [] // 出错时清空数据
    orderTotal.value = 0
  } finally {
    loadingOrders.value = false
  }
}

// 处理电影页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  console.log('电影当前页码:', page)
}

// 处理订单页码变化
const handleOrderPageChange = async (page: number) => {
  orderCurrentPage.value = page
  console.log('订单当前页码:', page)

  // 如果没有搜索条件，从服务器加载数据
  if (!orderNumberSearch.value && !orderUserSearch.value && !orderDateRange.value) {
    await loadOrdersFromServer()
  }
  // 有搜索条件时，使用本地过滤（由paginatedOrders计算属性处理）
}

// 过滤功能
const filteredMovies = computed(() => {
  // 如果没有任何搜索条件，返回所有电影
  if (!movieTitleSearch.value && !movieDirectorSearch.value && !movieStatusSearch.value && !movieSearchKeyword.value) {
    return movies.value
  }

  // 使用搜索字段进行过滤
  return movies.value.filter(movie => {
    // 电影名称搜索
    const titleMatch = !movieTitleSearch.value ||
      movie.title.toLowerCase().includes(movieTitleSearch.value.toLowerCase())

    // 导演搜索
    const directorMatch = !movieDirectorSearch.value ||
      movie.director.toLowerCase().includes(movieDirectorSearch.value.toLowerCase())

    // 状态搜索
    const statusMatch = !movieStatusSearch.value ||
      (movie.status && isStatusMatch(movie.status, movieStatusSearch.value))

    // 兼容旧的搜索关键字
    const keywordMatch = !movieSearchKeyword.value ||
      movie.title.toLowerCase().includes(movieSearchKeyword.value.toLowerCase()) ||
      movie.director.toLowerCase().includes(movieSearchKeyword.value.toLowerCase())

    // 所有条件都必须满足（AND 逻辑）
    return titleMatch && directorMatch && statusMatch && keywordMatch
  })
})

// 添加状态映射对象
const statusMap = {
  '上映中': ['上映中', '热映中'],
  '即将上映': ['即将上映', '预售中'],
  '已下架': ['已下架', '已结束']
}

// 电影状态是否匹配
const isStatusMatch = (movieStatus: string, selectedStatus: string) => {
  if (!selectedStatus || selectedStatus === '全部') return true

  const cleanMovieStatus = movieStatus.toLowerCase().trim()
  const cleanSelectedStatus = selectedStatus.toLowerCase().trim()

  // 完全匹配
  if (cleanMovieStatus === cleanSelectedStatus) return true

  // 检查是否属于同一主状态
  // 获取电影的主状态
  for (const key in statusMap) {
    if (cleanMovieStatus.includes(key.toLowerCase()) && key.toLowerCase() === cleanSelectedStatus) {
      return true
    }
  }

  return false
}

// 分页数据
const paginatedMovies = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredMovies.value.slice(start, end)
})

const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    // 订单编号筛选
    const orderNumberMatch = !orderNumberSearch.value ||
      (order.orderNumber && order.orderNumber.toLowerCase().includes(orderNumberSearch.value.toLowerCase())) ||
      order.id.toString().includes(orderNumberSearch.value);

    // 用户筛选
    const userMatch = !orderUserSearch.value ||
      (order.user?.username && order.user.username.toLowerCase().includes(orderUserSearch.value.toLowerCase()));

    // 电影名称筛选
    const movieMatch = !orderMovieSearch.value ||
      (order.movie?.title && order.movie.title.toLowerCase().includes(orderMovieSearch.value.toLowerCase()));

    // 日期筛选 - 修正：使用 order.orderTime 并进行日期对象比较
    const dateMatch = (() => {
      if (!orderDateRange.value) return true; // 没有选择日期范围则匹配
      if (!order.orderTime) return false; // 订单没有时间则不匹配

      try {
        const orderDateTime = new Date(order.orderTime); // 解析订单时间字符串
        const startDate = orderDateRange.value[0];
        const endDate = orderDateRange.value[1];

        // 设置时间为当天的开始和结束，以包含选择的日期
        startDate.setHours(0, 0, 0, 0);
        endDate.setHours(23, 59, 59, 999);

        return orderDateTime >= startDate && orderDateTime <= endDate;
      } catch (e) {
        console.error('日期解析或比较错误:', e);
        return false; // 解析失败则不匹配
      }
    })();

    // 所有条件都必须满足（AND 逻辑）
    return orderNumberMatch && userMatch && movieMatch && dateMatch;
  });
})

// 订单分页数据 - 使用服务器分页，不再本地分页
const paginatedOrders = computed(() => {
  // 如果有搜索条件，使用本地过滤后的数据
  if (orderNumberSearch.value || orderUserSearch.value || orderMovieSearch.value || orderDateRange.value) {
    const start = (orderCurrentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredOrders.value.slice(start, end)
  }
  // 没有搜索条件时，直接使用从服务器获取的数据
  return orders.value
})

// 格式化日期
const formatDate = (date: string | Date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 获取订单状态文本和类型
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    '待支付': 'warning',
    '已完成': 'success',
    '已取消': 'info'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    '待支付': 'warning',
    '已完成': 'success',
    '已取消': 'info'
  }
  return typeMap[status] || ''
}

// 电影管理相关变量
const movieDialogVisible = ref(false)
const isEditingMovie = ref(false)
const submittingMovie = ref(false)
const movieFormRef = ref()

// 电影表单
const movieForm = ref({
  id: 0,
  title: '',
  director: '',
  actors: '',
  genre: '',
  releaseDate: '',
  duration: 120,
  description: '',
  status: '正在热映'
})

// 表单验证规则
const movieRules = {
  title: [{ required: true, message: '请输入电影名称', trigger: 'blur' }],
  director: [{ required: true, message: '请输入导演', trigger: 'blur' }],
  releaseDate: [{ required: true, message: '请选择上映日期', trigger: 'change' }],
  duration: [{ required: true, message: '请输入电影片长', trigger: 'blur' }],
  status: [{ required: true, message: '请选择电影状态', trigger: 'change' }]
}

// 电影管理
const showAddMovieDialog = () => {
  isEditingMovie.value = false
  movieForm.value = {
    id: 0,
    title: '',
    director: '',
    actors: '',
    genre: '',
    releaseDate: '',
    duration: 120,
    description: '',
    status: '正在热映'
  }
  movieDialogVisible.value = true
}

const editMovie = (movie: Movie) => {
  isEditingMovie.value = true
  // 修正：为可选字段提供默认值
  movieForm.value = {
    ...movie,
    actors: movie.actors ?? '',
    genre: movie.genre ?? '',
    description: movie.description ?? '',
  }
  movieDialogVisible.value = true
}

const submitMovieForm = async () => {
  if (!movieFormRef.value) return

  await movieFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submittingMovie.value = true
      try {
        if (isEditingMovie.value) {
          // 更新现有电影
          await axiosInstance.put(`/admin/movies/${movieForm.value.id}`, movieForm.value)
          ElMessage.success('电影信息更新成功')

          // 更新本地数据
          const index = movies.value.findIndex(m => m.id === movieForm.value.id)
      if (index !== -1) {
            movies.value[index] = { ...movieForm.value }
          }
      } else {
          // 添加新电影
          const response = await axiosInstance.post('/admin/movies', movieForm.value)
          ElMessage.success('电影添加成功')

          // 添加到本地数据
          movies.value.push(response.data)
        }

        movieDialogVisible.value = false
      } catch (error: any) {
        console.error('保存电影数据失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败，请重试')
      } finally {
        submittingMovie.value = false
      }
    }
  })
}

const deleteMovie = (movie: Movie) => {
  ElMessageBox.confirm(`确定要删除电影"${movie.title}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axiosInstance.delete(`/admin/movies/${movie.id}`)
      ElMessage.success('删除成功')

      // 从本地数据中移除
      const index = movies.value.findIndex(m => m.id === movie.id)
      if (index !== -1) {
        movies.value.splice(index, 1)
      }
    } catch (error) {
      console.error('删除电影失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    // 用户取消删除操作
  })
}

// 影评管理相关函数
const loadReviewsFromServer = async () => {
  console.log('[loadReviewsFromServer] Started. Current page:', reviewCurrentPage.value); // 日志：函数开始
  try {
    // 准备查询参数
    const params: Record<string, any> = {
      page: reviewCurrentPage.value - 1, // 使用 0 索引页码
      size: pageSize.value,
    };

    // 添加筛选条件到参数中 (需要后端支持这些参数)
    if (reviewMovieTitleSearch.value) {
      params.movieTitle = reviewMovieTitleSearch.value;
    }
    if (reviewUserSearch.value) {
      params.username = reviewUserSearch.value;
    }
    // 确保评分值存在且不为 null
    if (reviewRatingSearch.value !== null) {
      // 直接赋值，因为 v-model 绑定的是 number
      params.rating = reviewRatingSearch.value;
    }

    console.log('[loadReviewsFromServer] Requesting with params:', params); // 日志：请求参数

    const response = await axiosInstance.get('/admin/reviews/paged', { params })
    console.log('[loadReviewsFromServer] Response received:', response.data); // 日志：收到响应

    if (response.data) {
      reviews.value = response.data.content || [] // 假设响应包含 content 数组
      reviewTotal.value = response.data.totalElements || 0 // 假设响应包含 totalElements
      console.log('[loadReviewsFromServer] Reviews data set. Total:', reviewTotal.value); // 日志：数据已设置
    } else {
      reviews.value = []
      reviewTotal.value = 0
      console.log('[loadReviewsFromServer] Response data is empty.'); // 日志：响应数据为空
    }
  } catch (error) {
    console.error('加载影评数据失败 [loadReviewsFromServer]:', error); // 日志：捕获到错误
    ElMessage.error('加载影评数据失败');
    reviews.value = [] // 出错时清空数据
    reviewTotal.value = 0
  }
  console.log('[loadReviewsFromServer] Finished.'); // 日志：函数结束
}

const searchReviews = () => {
  reviewCurrentPage.value = 1 // 重置到第一页
  loadReviewsFromServer()
}

const resetReviewSearch = () => {
  reviewMovieTitleSearch.value = ''
  reviewUserSearch.value = ''
  reviewRatingSearch.value = null
  searchReviews()
}

const handleReviewPageChange = (page: number) => {
  reviewCurrentPage.value = page
  loadReviewsFromServer()
}

const deleteReview = (review: Review) => {
  ElMessageBox.confirm('确定要删除这条影评吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 修改为调用管理员删除接口
      await axiosInstance.delete(`/admin/reviews/${review.id}`)
      ElMessage.success('删除影评成功')

      // 重新加载当前页数据以更新列表
      loadReviewsFromServer()
  } catch (error) {
      console.error('删除影评失败:', error)
      ElMessage.error('删除影评失败，请重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 计算属性
const paginatedReviews = computed(() => {
  // 如果后端已经分页，直接返回reviews
  return reviews.value
})

// 订单详情对话框相关变量已移除

// 订单详情功能已移除

// 添加取消订单函数
const cancelOrder = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 ${order.orderNumber} 吗？此操作将释放对应的座位。`,
      '取消订单确认',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用管理员取消订单接口
    await axiosInstance.post(`/admin/orders/${order.id}/cancel`)
    ElMessage.success('订单取消成功')

    // 刷新订单列表
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败，请重试')
    }
  }
}

// 添加刷新订单列表函数
const refreshOrders = () => {
  orderCurrentPage.value = 1
  loadOrdersFromServer()
}



// 显示添加场次对话框
const showAddShowtimeDialog = () => {
  isEditingShowtime.value = false
  // 重置表单
  showtimeForm.value = {
    id: 0,
    movieId: null,
    hallName: '1号厅',
    showTime: '',
    price: 50.00,
    availableSeats: 100
  }
  showtimeDialogVisible.value = true
  // 清除之前的验证状态 (如果需要)
  nextTick(() => {
      showtimeFormRef.value?.clearValidate();
  });
};

// 编辑场次
const editShowtime = (showtime: any) => {
  isEditingShowtime.value = true
  // 填充表单数据
  showtimeForm.value = {
    id: showtime.id,
    movieId: showtime.movie?.id || null,
    hallName: showtime.hallName || '1号厅',
    showTime: showtime.showTime || '',
    price: showtime.price || 50.00,
    availableSeats: 100  // 固定为100个座位
  }
  showtimeDialogVisible.value = true
  // 清除之前的验证状态 (如果需要)
  nextTick(() => {
      showtimeFormRef.value?.clearValidate();
  });
};

// 提交场次表单
const submitShowtimeForm = async () => {
  if (!showtimeFormRef.value) return;

  await showtimeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submittingShowtime.value = true;
      try {
        // 确保座位数始终为100
        showtimeForm.value.availableSeats = 100;

        if (isEditingShowtime.value) {
          // 调用后端接口更新场次
          await axiosInstance.put(`/admin/showtimes/${showtimeForm.value.id}`, showtimeForm.value);
          ElMessage.success('场次修改成功');
          showtimeDialogVisible.value = false;
          // 操作成功后，刷新场次列表
          loadShowtimesFromServer();
        } else {
          // 调用后端接口创建场次
          await axiosInstance.post('/admin/showtimes', showtimeForm.value);
          ElMessage.success('场次添加成功');
          showtimeDialogVisible.value = false;
          // 操作成功后，刷新场次列表
          loadShowtimesFromServer();
        }
      } catch (error: any) {
        console.error(isEditingShowtime.value ? '修改场次失败:' : '添加场次失败:', error);

        // 获取错误信息
        let errorMessage = '操作失败，请重试';
        if (error.response && error.response.data && error.response.data.message) {
          errorMessage = error.response.data.message;
        }

        // 显示错误信息
        ElMessage({
          message: errorMessage,
          type: 'error',
          duration: 5000 // 显示时间更长，让用户有足够时间阅读
        });
      } finally {
        submittingShowtime.value = false;
      }
    }
  });
};

// 从服务器加载场次数据
const loadShowtimesFromServer = async () => {
  loadingShowtimes.value = true;
  try {
    // 准备查询参数
    const params: Record<string, any> = {
      page: showtimeCurrentPage.value - 1, // 后端从0开始计数
      size: pageSize.value,
    };

    // 添加搜索条件
    if (showtimeMovieSearch.value) {
      params.movieId = showtimeMovieSearch.value;
    }

    if (showtimeHallSearch.value) {
      params.hallName = showtimeHallSearch.value;
    }

    if (showtimeDateRange.value && showtimeDateRange.value.length === 2) {
      const [startDate, endDate] = showtimeDateRange.value;
      params.startDate = startDate.toISOString().split('T')[0];
      params.endDate = endDate.toISOString().split('T')[0];
    }

    // 调用后端分页接口
    const response = await axiosInstance.get('/admin/showtimes/paged', { params });

    if (response.data) {
      showtimes.value = response.data.content || [];
      showtimeTotal.value = response.data.totalElements || 0;
    }
  } catch (error) {
    console.error('加载场次数据失败:', error);
    ElMessage.error('加载场次数据失败');
  } finally {
    loadingShowtimes.value = false;
  }
};

// 处理场次页码变化
const handleShowtimePageChange = (page: number) => {
  showtimeCurrentPage.value = page;
  loadShowtimesFromServer();
};

// 场次搜索函数
const searchShowtimes = () => {
  showtimeCurrentPage.value = 1; // 重置为第一页
  loadShowtimesFromServer();
};

// 重置场次搜索
const resetShowtimeSearch = () => {
  showtimeMovieSearch.value = null;
  showtimeHallSearch.value = '';
  showtimeDateRange.value = null;
  showtimeCurrentPage.value = 1; // 重置为第一页
  loadShowtimesFromServer();
};

// 删除场次
const deleteShowtime = (showtime: any) => {
  ElMessageBox.confirm(`确定要删除该场次吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axiosInstance.delete(`/admin/showtimes/${showtime.id}`);
      ElMessage.success('场次删除成功');

      // 刷新场次列表
      loadShowtimesFromServer();
    } catch (error: any) {
      console.error('删除场次失败:', error);
      ElMessage.error(error.response?.data?.message || '删除场次失败，请重试');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 获取电影时长的函数
const getMovieDuration = (movieId: number): number => {
  // 从已加载的电影列表中查找电影
  const movie = movies.value.find(m => m.id === movieId);
  return movie?.duration || 120; // 如果找不到电影或没有时长信息，默认为120分钟
};

// 格式化场次时间，显示为"开始时间-结束时间"
const formatShowtime = (showtime: string, movie?: any) => {
  if (!showtime) return '';

  // 解析开始时间
  const startDate = new Date(showtime);
  const startYear = startDate.getFullYear();
  const startMonth = String(startDate.getMonth() + 1).padStart(2, '0');
  const startDay = String(startDate.getDate()).padStart(2, '0');
  const startHours = String(startDate.getHours()).padStart(2, '0');
  const startMinutes = String(startDate.getMinutes()).padStart(2, '0');

  // 计算结束时间（开始时间 + 电影时长）
  const endDate = new Date(startDate);
  // 优先使用传入的电影对象的时长，如果没有则通过电影ID查找
  let duration = movie?.duration;
  if (!duration && movie?.id) {
    duration = getMovieDuration(movie.id);
  }
  duration = duration || 120; // 如果仍然没有时长信息，默认为120分钟

  endDate.setMinutes(endDate.getMinutes() + duration);

  const endHours = String(endDate.getHours()).padStart(2, '0');
  const endMinutes = String(endDate.getMinutes()).padStart(2, '0');

  // 返回格式化的时间字符串：YYYY-MM-DD HH:MM-HH:MM
  return `${startYear}-${startMonth}-${startDay} ${startHours}:${startMinutes}-${endHours}:${endMinutes}`;
};

// 计算属性
// 添加一个计算属性，只包含正在热映的电影
const nowPlayingMovies = computed(() => {
  return movies.value.filter(movie => movie.status === '正在热映');
});

// 场次分页数据
const paginatedShowtimes = computed(() => {
  return showtimes.value;
});

// 用户管理相关函数
const loadUsersFromServer = async () => {
  loadingUsers.value = true;
  try {
    const response = await adminUserApi.getUsers(userCurrentPage.value, userPageSize.value, userKeywordSearch.value || undefined);
    users.value = response.content || [];
    userTotal.value = response.totalElements || 0;
  } catch (error) {
    console.error('加载用户数据失败:', error);
    ElMessage.error('加载用户数据失败');
  } finally {
    loadingUsers.value = false;
  }
};

const searchUsers = () => {
  userCurrentPage.value = 1;
  loadUsersFromServer();
};

const resetUserSearch = () => {
  userKeywordSearch.value = '';
  userCurrentPage.value = 1;
  loadUsersFromServer();
};

const handleUserPageChange = (page: number) => {
  userCurrentPage.value = page;
  loadUsersFromServer();
};

const handleUserSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection;
};

const viewUserDetail = (user: any) => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <p><strong>用户ID:</strong> ${user.id}</p>
      <p><strong>用户名:</strong> ${user.username}</p>
      <p><strong>邮箱:</strong> ${user.email || '未设置'}</p>
      <p><strong>手机号:</strong> ${user.phone || '未设置'}</p>
      <p><strong>地址:</strong> ${user.address || '未设置'}</p>
      <p><strong>余额:</strong> ¥${user.balance?.toFixed(2) || '0.00'}</p>
      <p><strong>注册时间:</strong> ${formatDateTime(user.registerTime)}</p>
    </div>
  `, '用户详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定'
  });
};

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 数据统计相关函数
const loadStatsData = async () => {
  try {
    // 加载总体统计数据
    const overviewResponse = await adminStatsApi.getOverviewStats();
    overviewStats.value = overviewResponse;

    // 加载用户增长数据
    const userGrowthResponse = await adminStatsApi.getUserGrowthStats();
    userGrowthData.value = userGrowthResponse.growthData || [];

    // 加载收入数据
    const revenueResponse = await adminStatsApi.getRevenueStats();
    revenueData.value = revenueResponse.revenueData || [];

    // 加载热门电影数据
    const popularMoviesResponse = await adminStatsApi.getPopularMovies();
    popularMovies.value = popularMoviesResponse.popularMovies || [];

    // 加载用户分布数据
    const userDistributionResponse = await adminStatsApi.getUserDistribution();
    userDistribution.value = userDistributionResponse;

    // 初始化图表
    await nextTick();
    initCharts();
  } catch (error) {
    console.error('加载统计数据失败:', error);
    ElMessage.error('加载统计数据失败，显示模拟数据');
    
    // 提供默认的模拟数据
    overviewStats.value = {
      totalUsers: 2,
      totalMovies: 25,
      totalOrders: 1580,
      totalRevenue: 156800.50,
      todayOrders: 45,
      todayRevenue: 4580.00,
      activeUsers: 1
    };
    
    // 模拟用户增长数据
    userGrowthData.value = [
      { date: '12-01', newUsers: 15, activeUsers: 85 },
      { date: '12-02', newUsers: 12, activeUsers: 92 },
      { date: '12-03', newUsers: 18, activeUsers: 78 },
      { date: '12-04', newUsers: 22, activeUsers: 95 },
      { date: '12-05', newUsers: 8, activeUsers: 88 },
      { date: '12-06', newUsers: 25, activeUsers: 102 },
      { date: '12-07', newUsers: 19, activeUsers: 96 }
    ];
    
    // 模拟收入数据
    revenueData.value = [
      { date: '12-01', revenue: 3200, orders: 32 },
      { date: '12-02', revenue: 4100, orders: 41 },
      { date: '12-03', revenue: 2800, orders: 28 },
      { date: '12-04', revenue: 5200, orders: 52 },
      { date: '12-05', revenue: 3600, orders: 36 },
      { date: '12-06', revenue: 6800, orders: 68 },
      { date: '12-07', revenue: 4580, orders: 45 }
    ];
    
    // 模拟热门电影数据
    popularMovies.value = [
      { title: '沙丘2', ticketsSold: 294, revenue: 65384.65, rating: 8.9 },
      { title: '死侍与金刚狼', ticketsSold: 653, revenue: 23294.03, rating: 8.3 },
      { title: '花月杀手', ticketsSold: 588, revenue: 45799.40, rating: 9.8 },
      { title: '奥本海默', ticketsSold: 414, revenue: 56236.08, rating: 9.2 },
      { title: '心灵捕手2', ticketsSold: 520, revenue: 57421.98, rating: 9.4 }
    ];
    
    // 模拟用户分布数据
    userDistribution.value = {
      ageDistribution: [
        { ageGroup: '18-25', count: 35 },
        { ageGroup: '26-35', count: 45 },
        { ageGroup: '36-45', count: 25 },
        { ageGroup: '46-55', count: 15 },
        { ageGroup: '55+', count: 8 }
      ],
      regionDistribution: [
        { region: '北京', count: 25 },
        { region: '上海', count: 20 },
        { region: '广州', count: 15 },
        { region: '深圳', count: 12 },
        { region: '杭州', count: 10 },
        { region: '其他', count: 18 }
      ]
    };
  }
};

const initCharts = () => {
  // 这里可以使用 ECharts 或其他图表库来初始化图表
  // 由于没有安装图表库，这里只是占位符
  console.log('初始化图表...');
  
  // 示例：如果使用 ECharts
  // import * as echarts from 'echarts';
  // 
  // if (userGrowthChart.value) {
  //   const chart = echarts.init(userGrowthChart.value);
  //   chart.setOption({
  //     // 图表配置
  //   });
  // }
};

// 计算属性
</script>

<style scoped>
.admin-container {
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
  padding: 20px;
  display: flex;
}

.el-aside {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  height: calc(100vh - 100px);
  position: fixed;
  top: 80px;
  left: 20px;
  z-index: 100;
}

.admin-menu {
  height: 100%;
  border-right: none;
}

.el-main {
  background-color: #fff;
  margin-left: 180px;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 140px);
}

.larger-font-table {
  font-size: 14px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-actions {
  display: flex;
  align-items: center;
}

.selection-info {
  margin-left: 10px;
  color: #606266;
}

.search-container {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .action-bar {
  flex-direction: column;
  align-items: flex-start;
  }

  .search-container {
    margin-top: 10px;
    flex-wrap: wrap;
  }

  .el-input, .el-select {
  margin-bottom: 10px;
}
}

.review-content-cell {
  text-align: center;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 400px;
  margin: 0 auto;
}

/* 订单管理样式 */
.orders-management {
  width: 100%;
}

.order-search {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 用户管理样式 */
.users-management {
  width: 100%;
}

/* 数据统计样式 */
.stats-management {
  width: 100%;
}

.stats-overview {
  margin-bottom: 30px;
}

.stats-card {
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-item {
  padding: 20px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #606266;
}

.stats-charts .el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.chart-container {
  height: 250px;
  padding: 20px;
}

.simple-chart {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  height: 180px;
  border-bottom: 2px solid #e4e7ed;
  padding: 0 10px;
}

.chart-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  margin: 0 5px;
}

.chart-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 5px;
  text-align: center;
}

.chart-bar-container {
  width: 30px;
  height: 120px;
  display: flex;
  align-items: flex-end;
  position: relative;
}

.chart-bar {
  width: 100%;
  background-color: #409EFF;
  border-radius: 2px 2px 0 0;
  transition: all 0.3s ease;
  min-height: 5px;
}

.chart-bar:hover {
  opacity: 0.8;
}

.chart-value {
  font-size: 12px;
  color: #303133;
  margin-top: 5px;
  text-align: center;
}

.revenue-bar {
  background-color: #67C23A;
}

.distribution-container {
  padding: 20px;
}

.distribution-section {
  margin-bottom: 30px;
}

.distribution-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.distribution-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.distribution-label {
  width: 80px;
  font-size: 14px;
  color: #606266;
  text-align: right;
  margin-right: 15px;
}

.distribution-bar-container {
  flex: 1;
  height: 20px;
  background-color: #f5f7fa;
  border-radius: 10px;
  overflow: hidden;
  margin-right: 10px;
}

.distribution-bar {
  height: 100%;
  background-color: #409EFF;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.distribution-value {
  width: 40px;
  font-size: 12px;
  color: #303133;
  text-align: center;
}

.region-bar {
  background-color: #E6A23C;
}
</style>
